<template>
  <section class="login-page">
    <div class="login-card">
      <h1 class="login-title">登录</h1>
      <p class="login-subtitle">使用你的账号进入知识库</p>
      <form class="login-form" @submit.prevent="onSubmit">
        <div class="form-item">
          <label>用户名</label>
          <input v-model="username" required />
        </div>
        <div class="form-item">
          <label>密码</label>
          <input v-model="password" type="password" required />
        </div>
        <button class="login-button" type="submit" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>
      <p v-if="error" class="login-error">{{ error }}</p>
    </div>
  </section>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';

const username = ref('admin');
const password = ref('admin');
const loading = ref(false);
const error = ref('');
const router = useRouter();

async function onSubmit() {
  loading.value = true;
  error.value = '';
  try {
    const res = await fetch('/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: username.value, password: password.value }),
    });

    if (!res.ok) {
      const data = await res.json().catch(() => ({}));
      throw new Error(data.error || '登录失败');
    }

    await res.json();
    router.push('/notes');
  } catch (e) {
    error.value = e.message || '登录失败';
  } finally {
    loading.value = false;
  }
}
</script>

<style scoped>
.login-page {
  min-height: calc(100vh - 60px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-card {
  width: 100%;
  max-width: 360px;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  padding: 24px 20px 20px;
  background: #ffffff;
  box-shadow: 0 10px 30px rgba(15, 23, 42, 0.06);
}

.login-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 4px;
}

.login-subtitle {
  font-size: 13px;
  color: #6b7280;
  margin-bottom: 16px;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-item label {
  font-size: 13px;
  color: #4b5563;
}

.form-item input {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  padding: 8px 10px;
  font-size: 14px;
}

.form-item input:focus {
  outline: none;
  border-color: #111827;
}

.login-button {
  margin-top: 4px;
  border-radius: 999px;
  border: none;
  padding: 8px 12px;
  font-size: 14px;
  font-weight: 500;
  color: #f9fafb;
  background: #111827;
  cursor: pointer;
}

.login-button:disabled {
  opacity: 0.6;
  cursor: default;
}

.login-error {
  margin-top: 10px;
  font-size: 13px;
  color: #b91c1c;
}
</style>
